package com.blog.service.impl;

import com.alibaba.fastjson.JSON;
import com.blog.mapper.SearchMapper;
import com.blog.pojo.ArticleEs;
import com.blog.service.EsService;
import com.blog.service.SearchService;
import com.blog.pojo.Article;
import org.apache.dubbo.config.annotation.DubboReference;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.List;

@Service
public class SearchServiceImpl implements SearchService {
    @DubboReference
    private EsService esService;
    @Autowired
    private SearchMapper searchMapper;

    @Override
    public List<ArticleEs> search(String keyword) {
        MatchQueryBuilder query = QueryBuilders.matchQuery("title", keyword);
        Iterable<ArticleEs> search = searchMapper.search(query);
        ArrayList<ArticleEs> list = new ArrayList<>();
        for (ArticleEs articleEs : search) {
            list.add(articleEs);
        }
        return list;
    }

    @Override
    public void deploy() {
        List<Article> list = esService.findAll();
        String jsonString = JSON.toJSONString(list);
        List<ArticleEs> articleEs = JSON.parseArray(jsonString, ArticleEs.class);
        searchMapper.saveAll(articleEs);
    }

}
